<template>
  <li :class="['chat-message', { isSelf: msg.isSelf }]">
    <div class="innerbox">
      <template v-if="msg.isSelf">
        <div v-if="msg.error" class="error">
          <ElIcon :size="20">
            <Warning />
          </ElIcon>
        </div>
        <div v-else-if="msg.loading" class="loading">
          <ElIcon class="is-loading" :size="20">
            <Loading />
          </ElIcon>
        </div>
      </template>
      <template v-if="!msg.isSelf">
        <ElAvatar class="robot-avatar" :src="msg.icon" />
        <div v-if="reference" class="reference">
          <ElPopover placement="top-start" :width="360">
            <template #reference>
              <ElIcon :size="14">
                <InfoFilled />
              </ElIcon>
            </template>
            <div v-html="reference" class="chat-message-reference-box"></div>
          </ElPopover>
        </div>
      </template>
      <div class="content" v-html="msg.content"></div>
      <ElAvatar v-if="msg.isSelf" :icon="User" />
    </div>
  </li>
</template>

<script setup>
import { ElIcon, ElAvatar, ElPopover } from 'element-plus'
import { Loading, User, InfoFilled, Warning } from '@element-plus/icons-vue'
import { computed } from 'vue';

const props = defineProps({ msg: {} })
const reference = computed(() => {
  const strs = props.msg.source_documents
  if (strs && strs.length) {
    return '<ul>' + strs.map(_ => `<li>${_.replace(/\n/gm, '<br>')}</li>`) + '</ul>'
  }
  return ''
})
</script>

<style lang="scss">
.chat-message {
  list-style: none;
  margin-bottom: 24px;
  .innerbox {
    position: relative;
    display: inline-flex;
    align-items: flex-start;
    max-width: 70%;
    .content {
      padding: 8px 10px;
      word-break: break-all;
      border-radius: 6px;
      line-height: 1.6;
      background-color: var(--el-color-primary-light-9);
    }
    .el-avatar {
      min-width: 40px;
    }
    .robot-avatar {
      background: none;
      margin-right: 6px;
    }
    .reference {
      position: absolute;
      right: 0;
      bottom: 0;
      transform: translateY(100%);
      color: var(--el-text-color-secondary);
    }
  }
  &.isSelf {
    text-align: right;
    .innerbox {
      text-align: left;
      .content {
        background-color: var(--el-color-info-light-9);
        margin-right: 10px;
      }
    }
    .loading, .error {
      display: flex;
      position: absolute;
      top: 50%;
      left: 0;
      transform: translate(-120%, -50%);
    }
    .error {
      color: var(--el-color-danger);
    }
  }
}

.chat-message-reference-box {
  max-height: 240px;
  overflow-y: auto;
  line-height: 1.6;
}
</style>
